<template>
  <div class="shop-list-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal"> </FilterTable>
    </div>
    <div class="table-gl-con mt10">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-space>
            <a-button class="gray-outline" @click="show('add')">新增店铺</a-button>
            <a-button class="gray-outline" @click="ShopManager">设置店长</a-button>
            <a-button class="gray-outline" @click="shopAssistant">设置店员</a-button>
            <a-button class="gray-outline" @click="shopBrand">关联品牌</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table :data="tableData" size="mini" row-key="id" v-model:selected-keys="ids" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-single-line" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column type="index" title="序号" :width="40" #cell="{ rowIndex }">{{ rowIndex + 1 }}</a-table-column>
              <a-table-column title="店铺ID" #cell="{ record }" :width="40">{{ record.sellerId }}</a-table-column>
              <a-table-column title="店铺名称" #cell="{ record }" :width="80">
                <TextLimit position="top" :val="record.shopName"></TextLimit>
              </a-table-column>
              <a-table-column title="网站域名" #cell="{ record }" :width="120">
                <TextLimit position="top" :val="record.wooCommerceUrl"></TextLimit>
              </a-table-column>
              <a-table-column title="品牌" #cell="{ record }" :width="80">
                {{ showBrandName(record) }}
              </a-table-column>
              <a-table-column title="店长" #cell="{ record }" :width="80">
                {{ showShopMastersName(record.shopMasters, 'master') }}
              </a-table-column>
              <!-- <a-table-column title="店员" #cell="{ record }" :width="80">
                {{ showShopMastersName(record.shopMasters, 'clerk') }}
              </a-table-column> -->
              <a-table-column title="状态" #cell="{ record }" :width="80">
                <a-space>
                  <a-switch v-model="record.wooCommerceOpen" @change="changeStatus(record)">
                    <template #checked>开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                  <div>{{ record.wooCommerceOpen ? '已启用' : '已禁用' }}</div>
                </a-space>
              </a-table-column>
              <a-table-column title="创建时间" #cell="{ record }" :width="120">
                {{ $setTime(record.gmtCreate) }}
              </a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="40">
                <a-button type="text" @click="show('edit', record)">编辑</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <shopDetail v-if="showShopDtailModal" v-model="showShopDtailModal" :type="type" :info="info" @save="getList" />
  <setShopManager v-if="showsetShopManagerModal" v-model="showsetShopManagerModal" :ids="ids" @save="saveData" />
  <setShopAssistant v-if="showsetShopAssistantModal" v-model="showsetShopAssistantModal" :list="tableData" :ids="ids" @save="saveData" />
  <setShopBrand v-if="showsetShopBrandModal" v-model="showsetShopBrandModal" :ids="ids" @save="saveData" />
</template>

<script lang="ts" setup>
  import { defineComponent, ref, onMounted } from 'vue'
  import { listAllUserWordPressShop } from '@/api/product'
  import { getOrganizesUser, findShopPageByParam, updateShopBaseV2 } from '@/api/system'
  import { Message } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import shopDetail from './components/shopDetail.vue'
  import setShopManager from './components/setShopManager.vue'
  import setShopAssistant from './components/setShopAssistant.vue'
  import setShopBrand from './components/setShopBrand.vue'
  const filterItem: any = ref([
    {
      type: 'input_search',
      key: 'shopName',
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入店铺名称',
      label: '店铺名称',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_search',
      key: 'sellerId',
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入SellerID',
      label: '店铺ID',
      width: 200,
      isMultiple: true,
    },
    {
      key: 'masterIds',
      label: '店长',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [{ label: '创建时间', value: 'gmtCreate' }],
      keyWidth: '110',
      label: '创建时间',
      value: ref(),
      width: 300,
    },
  ])
  let tableData = ref([{}])
  let loading = ref(false)
  let showShopDtailModal = ref(false)
  let showsetShopManagerModal = ref(false)
  let showsetShopAssistantModal = ref(false)
  let showsetShopBrandModal = ref(false)
  let ids = ref([])
  let searchValue = ref({})
  let type = ref('add')
  let info = ref({})
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })

  const getUSerList = async () => {
    let params = {
      depart: false,
      needRole: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    if (res) {
      let arr = res.data.records || []
      filterItem.value[2].optionItems = arr.map((e: any) => {
        e.label = e.userName
        e.value = e.id
        return e
      })
    }
  }
  // 显示弹框
  const show = (showType: string, data?: any) => {
    type.value = showType
    info.value = data
    showShopDtailModal.value = true
  }

  const changeStatus = async (record: any) => {
    let params = {
      wooCommerceOpen: record.wooCommerceOpen,
      idList: [record.id],
    }
    const res: any = await updateShopBaseV2(params)
    if (res) {
      Message.success('状态编辑成功')
    }
  }
  const ShopManager = async () => {
    if (!ids.value[0]) return Message.error('请选择要设置店长的数据')
    showsetShopManagerModal.value = true
  }
  const shopAssistant = async () => {
    if (!ids.value[0]) return Message.error('请选择要设置店员的数据')
    showsetShopAssistantModal.value = true
  }
  const shopBrand = async () => {
    if (!ids.value[0]) return Message.error('请选择要设置品牌的数据')
    showsetShopBrandModal.value = true
  }

  // 显示品牌名称
  const showBrandName = (item: any) => {
    return item?.shopBrands?.map((el: any) => el.brandName)?.join(',')
  }
  // 显示店长信息
  const showShopMastersName = (userList: any, roleType: string) => {
    let arr = userList || []
    return arr
      .filter((e: any) => e.role == roleType)
      .map((el: any) => el.userName)
      ?.join(',')
  }

  const saveData = () => {
    ids.value = []
    getList()
  }

  // 搜索
  const searchByVal = (info: any) => {
    searchValue.value = info
    getList()
  }
  // 分页
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const getList = async () => {
    let params: any = {
      ...searchValue.value,
      platform: 'wooCommerce',
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }

    if (params.startDate) {
      params.startDate = `${params.startDate} 00:00:00`
    }
    if (params.endDate) {
      params.endDate = `${params.endDate} 23:59:59`
    }

    loading.value = true
    const res: any = await listAllUserWordPressShop(params)
    if (res) {
      tableData.value = res.data || []
      pageNation.value.total = res.data.total
    }
    loading.value = false
  }

  onMounted(() => {
    getUSerList()
    getList()
  })
</script>

<style lang="less" scoped>
  .shop-list-con {
    height: calc(100vh - 80px);
  }
</style>
